package com.wjc.lib

/**
 * ClassName: com.wjc.lib
 * Description:
 * JcChen on 2021.04.22.15:25
 */

abstract class Handler {
    protected var successor: Handler? = null

    fun setSuccessor1(successor: Handler?) {
        if (successor != null)
            println("传入  successor=$successor,this=$this")
        this.successor = successor
    }

    open fun handle() {
        val handled = doHandle()
        println("handle --successor=$successor,this=$this")
        if (successor != null && handled) {
            successor!!.handle()
        }
    }

    protected abstract fun doHandle(): Boolean
}


class HandlerA : Handler() {


    override fun doHandle(): Boolean {
        val handled = false
        // xxx
        return !handled
    }
}

class HandlerB : Handler() {
    override fun doHandle(): Boolean {
        val handled = false
        // xxx
        return !handled
    }
}

class HandlerC : Handler() {
    override fun doHandle(): Boolean {
        val handled = false
        // xxx
        return !handled
    }
}

class HandlerChain {
    private var head: Handler? = null
    private var tail: Handler? = null
    fun addHandler(handler: Handler) {
        handler.setSuccessor1(null)
        if (head == null) {
            head = handler
            tail = handler
            println("first addHandler head=$head")
            return
        }
        tail!!.setSuccessor1(handler)
        tail = handler
//        println("addHandler tail=$tail")
    }

    fun handle() {
        println("handle first head=$head")
        if (head != null) {
            head!!.handle()
        }
    }
}

// 使用举例
object Application {
    @JvmStatic
    fun main(args: Array<String>) {
        val chain = HandlerChain()
        chain.addHandler(HandlerA())
        chain.addHandler(HandlerB())
        chain.addHandler(HandlerC())
        chain.handle()
    }
}